package com.ds.esd.admin;

import com.ds.cluster.ServerNode;
import com.ds.common.JDSException;
import com.ds.common.database.metadata.ProviderConfig;
import com.ds.common.util.StringUtility;
import com.ds.config.ErrorListResultModel;
import com.ds.config.ErrorResultModel;
import com.ds.config.ListResultModel;
import com.ds.config.ResultModel;
import com.ds.enums.db.MethodChinaName;
import com.ds.esd.admin.node.XUIProject;
import com.ds.esd.admin.plugins.fdt.node.UIDBConfigNode;
import com.ds.esd.client.ESDClient;
import com.ds.esd.client.ESDFacrory;
import com.ds.esd.client.Project;
import com.ds.esd.client.ProjectVersion;
import com.ds.esd.editor.enums.CustomMenuType;
import com.ds.esd.editor.extmenu.PluginsFactory;
import com.ds.esd.plugins.api.APIFactory;
import com.ds.esd.plugins.api.enums.APIType;
import com.ds.esd.plugins.api.node.APIComponentNode;
import com.ds.esd.plugins.api.node.APIPaths;
import com.ds.esd.plugins.font.node.FontConfig;
import com.ds.esd.project.config.DataBaseConfig;
import com.ds.esd.project.config.ProjectConfig;
import com.ds.esd.project.enums.*;
import com.ds.esd.project.temp.ProjectTemp;
import com.ds.esd.tool.ui.component.data.APICallerProperties;
import com.ds.esd.workspace.MySpace;
import com.ds.esd.workspace.MySpaceConfig;
import com.ds.server.JDSServer;
import com.ds.vfs.FileInfo;
import com.ds.vfs.Folder;
import com.ds.web.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping(value = {"/admin/"})
@MethodChinaName(cname = "RAD工程管理")
public class ProjectManager {


    public ProjectManager() {

    }

    @MethodChinaName(cname = "获取工程分类")
    @RequestMapping(value = {"getTempType"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<ProjectTemp>> getTempType(String path, String pattern) {
        ListResultModel<List<ProjectTemp>> result = new ListResultModel<List<ProjectTemp>>();
        List<ProjectTemp> temps = new ArrayList<>();
        for (ProjectTempType type : ProjectTempType.values()) {
            ProjectTemp temp = new ProjectTemp(type);
            temps.add(temp);
        }
        result.setData(temps);

        return result;
    }


    @RequestMapping(value = {"projectManager"}, method = {RequestMethod.GET})
    @MethodChinaName(cname = "工程编辑")
    public ModelAndView projectManager(ModelAndView mv, HttpServletResponse response, String domainId, @PathVariable String projectName) {
        mv.addObject("projectName", projectName);
        List<String> modules = new ArrayList<String>();
        List<FileInfo> cssFiles = new ArrayList<FileInfo>();
        try {
            ProjectVersion version = getClient().getProjectVersionByName(projectName);
            PluginsFactory.getInstance().getAllTopMenu(CustomMenuType.top, domainId);
            List<FontConfig> fontNodes = version.getProject().getFonts();
            for (FontConfig fontNode : fontNodes) {
                Folder folder = getClient().getFolderByPath(fontNode.getFile());
                List<FileInfo> fileInfos = folder.getFileListRecursively();
                for (FileInfo cssFile : fileInfos) {
                    if (cssFile.getName().endsWith(".css")) {
                        if (!cssFiles.contains(cssFile)) {
                            cssFiles.add(cssFile);
                        }

                    }
                }
            }
            mv.addObject("cssFiles", cssFiles);
        } catch (JDSException e) {
            e.printStackTrace();
        }
        mv.setViewName("/projectManager");
        return mv;
    }

    @RequestMapping(value = {"debug"}, method = {RequestMethod.GET})
    @MethodChinaName(cname = "调试")
    public ModelAndView debug(ModelAndView mv, @PathVariable String projectName) {
        mv.addObject("projectName", projectName);
        List<FileInfo> cssFiles = new ArrayList<FileInfo>();
        try {
            ProjectVersion version = getClient().getProjectVersionByName(projectName);
            List<FontConfig> fontNodes = version.getProject().getFonts();
            for (FontConfig fontNode : fontNodes) {
                Folder folder = getClient().getFolderByPath(fontNode.getFile());
                List<FileInfo> fileInfos = folder.getFileListRecursively();
                for (FileInfo cssFile : fileInfos) {
                    if (cssFile.getName().endsWith(".css")) {
                        if (!cssFiles.contains(cssFile)) {
                            cssFiles.add(cssFile);
                        }

                    }
                }
            }
        } catch (JDSException e) {
            e.printStackTrace();
        }
        mv.addObject("cssFiles", cssFiles);
        mv.setViewName("/projectDebug");
        return mv;
    }


    @MethodChinaName(cname = "创建工程")
    @RequestMapping(value = {"createProject"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIProject> createProject(String projectName, String desc, String tempName, String url) {
        ResultModel<XUIProject> result = new ResultModel<XUIProject>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {
            if (tempName != null && projectName.equals(tempName)) {
                projectName = projectName + "1";
            }
            Project project = getClient().cloneProject(projectName, desc, tempName, ProjectDefAccess.Public);
            if (url != null) {
                project.getConfig().setPublicServerUrl(url);

            }
            project.getConfig().addDevPersons(ProjectRoleType.own, this.getClient().getConnectInfo().getUserID());
            project.updateConfig(project.getConfig());


            result.setData(new XUIProject(project));
        } catch (JDSException e) {
            e.printStackTrace();
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }

    @MethodChinaName(cname = "创建工程")
    @RequestMapping(value = {"updateProjectInfo"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIProject> updateProjectInfo(String projectName, String desc, String url, String indexPage) {
        ResultModel<XUIProject> result = new ResultModel<XUIProject>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {
            Project project = getClient().updateProjectInfo(projectName, desc);

            if (url != null || indexPage != null) {
                project.getConfig().setPublicServerUrl(url);
                project.getConfig().setIndex(indexPage);
                project.updateConfig(project.getConfig());
            }

            result.setData(new XUIProject(project));
        } catch (JDSException e) {
            e.printStackTrace();
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }

    @MethodChinaName(cname = "创建资源工程")
    @RequestMapping(value = {"createResourceProject"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIProject> createResourceProject(String projectName, String desc, ProjectResourceType type) {
        ResultModel<XUIProject> result = new ResultModel<XUIProject>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {

            // Project project = getClient().cloneProject(projectName, desc, null, ProjectDefAccess.Component);
            Project project = getClient().cloneResourceProject(projectName, desc, null, type);
            result.setData(new XUIProject(project));
        } catch (JDSException e) {
            e.printStackTrace();
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "获取工程")
    @RequestMapping(value = {"getResouceProjectList"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUIProject>> getResouceProjectList(ProjectResourceType type) {
        ListResultModel<List<XUIProject>> result = new ListResultModel<List<XUIProject>>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {
            List<Project> projects = this.getClient().getResourceAllProject(type);
            result = PageUtil.getDefaultPageList(projects, XUIProject.class);
        } catch (JDSException e) {
            e.printStackTrace();
        }
        return result;
    }


    @MethodChinaName(cname = "创建模块工程")
    @RequestMapping(value = {"createModuleComProject"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIProject> createModuleComProject(String projectName, String desc, String url) {
        ResultModel<XUIProject> result = new ResultModel<XUIProject>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {
            Project project = getClient().cloneProject(projectName, desc, null, ProjectDefAccess.Module);
            if (url != null) {
                project.getConfig().setPublicServerUrl(url);
                project.getConfig().addDevPersons(ProjectRoleType.own, this.getClient().getConnectInfo().getUserID());
                project.updateConfig(project.getConfig());
            }
            result.setData(new XUIProject(project));
        } catch (JDSException e) {
            e.printStackTrace();
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "获取模块工程")
    @RequestMapping(value = {"getModuleProjectList"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUIProject>> getModuleProjectList() {
        ListResultModel<List<XUIProject>> result = new ListResultModel<List<XUIProject>>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {
            List<Project> projects = this.getClient().getAllProject(ProjectDefAccess.Module);
            result = PageUtil.getDefaultPageList(projects, XUIProject.class);
        } catch (JDSException e) {
            e.printStackTrace();
        }
        return result;
    }


    @MethodChinaName(cname = "创建模板工程")
    @RequestMapping(value = {"createExtComProject"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIProject> createExtComProject(String projectName, String desc, String url) {
        ResultModel<XUIProject> result = new ResultModel<XUIProject>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {
            Project project = getClient().cloneProject(projectName, desc, null, ProjectDefAccess.ExtCom);
            if (url != null) {
                project.getConfig().setPublicServerUrl(url);
                project.getConfig().addDevPersons(ProjectRoleType.own, this.getClient().getConnectInfo().getUserID());
                project.updateConfig(project.getConfig());
            }
            result.setData(new XUIProject(project));
        } catch (JDSException e) {
            e.printStackTrace();
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "创建通用模块工程")
    @RequestMapping(value = {"createExtModuleProject"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIProject> createExtModuleProject(String projectName, String desc, String url) {
        ResultModel<XUIProject> result = new ResultModel<XUIProject>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {
            Project project = getClient().cloneProject(projectName, desc, null, ProjectDefAccess.Module);
            if (url != null) {
                project.getConfig().setPublicServerUrl(url);
                project.getConfig().addDevPersons(ProjectRoleType.own, this.getClient().getConnectInfo().getUserID());
                project.updateConfig(project.getConfig());
            }
            result.setData(new XUIProject(project));
        } catch (JDSException e) {
            e.printStackTrace();
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "获取模板工程")
    @RequestMapping(value = {"getExtComProjectList"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUIProject>> getExtComProjectList() {
        ListResultModel<List<XUIProject>> result = new ListResultModel<List<XUIProject>>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {
            List<Project> projects = this.getClient().getAllProject(ProjectDefAccess.ExtCom);
            result = PageUtil.getDefaultPageList(projects, XUIProject.class);
        } catch (JDSException e) {
            e.printStackTrace();
        }
        return result;
    }


    @MethodChinaName(cname = "获取模块工程")
    @RequestMapping(value = {"getExtModuleProjectList"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUIProject>> getExtModuleProjectList() {
        ListResultModel<List<XUIProject>> result = new ListResultModel<List<XUIProject>>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {
            List<Project> projects = this.getClient().getAllProject(ProjectDefAccess.Module);
            result = PageUtil.getDefaultPageList(projects, XUIProject.class);
        } catch (JDSException e) {
            e.printStackTrace();
        }
        return result;
    }


    @MethodChinaName(cname = "创建组件工程")
    @RequestMapping(value = {"createComponentProject"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIProject> createComponentProject(String projectName, String desc, String url) {
        ResultModel<XUIProject> result = new ResultModel<XUIProject>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {
            Project project = getClient().cloneProject(projectName, desc, null, ProjectDefAccess.Component);
            if (url != null) {
                project.getConfig().setPublicServerUrl(url);
                project.getConfig().addDevPersons(ProjectRoleType.own, this.getClient().getConnectInfo().getUserID());
                project.updateConfig(project.getConfig());
            }
            result.setData(new XUIProject(project));
        } catch (JDSException e) {
            e.printStackTrace();
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "获取组件工程")
    @RequestMapping(value = {"getComponentProjectList"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUIProject>> getComponentProjectList() {
        ListResultModel<List<XUIProject>> result = new ListResultModel<List<XUIProject>>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {
            List<Project> projects = this.getClient().getAllProject(ProjectDefAccess.Component);
            result = PageUtil.getDefaultPageList(projects, XUIProject.class);
        } catch (JDSException e) {
            e.printStackTrace();
        }
        return result;
    }


    @MethodChinaName(cname = "获取工程信息")
    @RequestMapping(value = {"getProjectInfo"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIProject> getProjectInfo(String projectName) {
        ResultModel<XUIProject> result = new ResultModel<XUIProject>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {

            Project project = getClient().getProjectByName(projectName);
            result.setData(new XUIProject(project));
        } catch (JDSException e) {
            e.printStackTrace();
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "创建模板工程")
    @RequestMapping(value = {"createTempProject"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIProject> createTempProject(String projectName, String desc) {
        ResultModel<XUIProject> result = new ResultModel<XUIProject>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {

            Project project = getClient().createProject(projectName, desc, ProjectDefAccess.Templat);
            result.setData(new XUIProject(project));
        } catch (JDSException e) {
            e.printStackTrace();
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "获取工程")
    @RequestMapping(value = {"getTempProjectList"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUIProject>> getTempProjectList(ProjectTempType type) {

        ListResultModel<List<XUIProject>> result = new ListResultModel<List<XUIProject>>();
        List<XUIProject> modules = new ArrayList<XUIProject>();


        try {
            List<Project> projects = new ArrayList<>();
            if (type == null) {
                type = ProjectTempType.Custom;
            }
            switch (type) {
                case Custom:
                    projects = this.getClient().getAllProject(ProjectDefAccess.Templat);
                    break;
                case OA:
                    projects = this.getClient().getAllProject(ProjectDefAccess.Templat);
                    break;
                case IOT:
                    break;
                case Clone:
                    projects = this.getClient().getAllProject(ProjectDefAccess.Public);
                    break;
                default:
                    projects = this.getClient().getAllProject(ProjectDefAccess.Templat);
                    break;
            }
            result = PageUtil.getDefaultPageList(projects, XUIProject.class);
        } catch (JDSException e) {
            e.printStackTrace();
        }
        return result;
    }


    @MethodChinaName(cname = "获取工程")
    @RequestMapping(value = {"getProjectList"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUIProject>> getProjectList(String pattern) {
        ListResultModel<List<XUIProject>> result = new ListResultModel<List<XUIProject>>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        try {
            List<Project> projects = getClient().getAllProject(ProjectDefAccess.Public);
            List<Project> projectList = new ArrayList<Project>();
            for (Project project : projects) {
                if (pattern != null && !pattern.equals("")) {
                    Pattern p = Pattern.compile(pattern);
                    Matcher matcher = p.matcher(project.getProjectName());
                    Matcher descmatcher = p.matcher(project.getDesc());
                    if (matcher.find() || descmatcher.find()) {
                        projectList.add(project);
                    }
                } else {
                    projectList.add(project);
                }

            }
            result = PageUtil.getDefaultPageList(projectList, XUIProject.class);
        } catch (JDSException e) {
            e.printStackTrace();
        }
        return result;
    }


    @MethodChinaName(cname = "获取工程分支数据")
    @RequestMapping(value = {"getProjectVersionList"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUIProject>> getProjectVersionList(String projectName, String pattern) {
        ListResultModel<List<XUIProject>> result = new ListResultModel<List<XUIProject>>();
        List<XUIProject> modules = new ArrayList<XUIProject>();
        Project project = null;
        try {
            project = getClient().getProjectByName(projectName);
            List<ProjectVersion> versions = new ArrayList<ProjectVersion>();
            for (ProjectVersion version : project.getAllEIProjectVersion()) {
                if (pattern != null && !pattern.equals("")) {
                    Pattern p = Pattern.compile(pattern);
                    Matcher matcher = p.matcher(version.getVersionName());
                    Matcher descmatcher = p.matcher(version.getDesc());
                    if (matcher.find() || descmatcher.find()) {
                        versions.add(version);
                    }
                } else {
                    versions.add(version);
                }

            }

            result = PageUtil.getDefaultPageList(versions, XUIProject.class);
        } catch (JDSException e) {
            e.printStackTrace();
        }

        return result;
    }


    @MethodChinaName(cname = "更新版本状态")
    @RequestMapping(value = {"versionStatusAction"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> versionStatusAction(String versionName, ProjectVersionStatus status) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {
            ProjectVersion projectVersion = getClient().getProjectVersionByName(versionName);

            if (status != null && projectVersion != null) {
                switch (status) {
                    case RELEASED:
                        projectVersion.activateProjectVersion();
                        break;
                    case CLEAR:
                        projectVersion.delete();
                        break;
                    case DELETEED:
                        projectVersion.delete();
                        break;
                    case UNDERREVISION:
                        projectVersion.freezeProjectVersion();
                        break;

                }
            }
            result.setData(true);
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "新增版本")
    @RequestMapping(value = {"createVersion"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIProject> createVersion(String projectName) {
        ResultModel<XUIProject> result = new ResultModel<XUIProject>();
        try {
            // ProjectVersion projectVersion = getClient().getProjectVersionByName(projectName);
            ProjectVersion projectVersion = getClient().createProcessVersion(projectName);
            result.setData(new XUIProject(projectVersion));
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "删除工程版本")
    @RequestMapping(value = {"delProjectVersion"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> delProjectVersion(String versionName) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();

        try {
            ProjectVersion projectVersion = getClient().getProjectVersionByName(versionName);
            getClient().delProject(versionName);
        } catch (JDSException e) {
            e.printStackTrace();
        }
        return result;
    }

    @MethodChinaName(cname = "删除工程版本")
    @RequestMapping(value = {"delProject"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> delProject(String id) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {
            String[] ids = StringUtility.split(id, ";");
            for (String projectId : ids) {
                getClient().delProject(projectId);
            }
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "加载数据库配置")
    @RequestMapping(value = {"getDbConfigTree"}, method = {RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<UIDBConfigNode>> getDbConfigTree() {
        ListResultModel<List<UIDBConfigNode>> result = new ListResultModel<List<UIDBConfigNode>>();
        try {
            List<UIDBConfigNode> uidbConfigNodes = new ArrayList<UIDBConfigNode>();
            List<ProviderConfig> configs = getClient().getAllDbConfig();

            for (ProviderConfig config : configs) {
                uidbConfigNodes.add(new UIDBConfigNode(config));
            }


            result.setData(uidbConfigNodes);
        } catch (JDSException e) {
            result = new ErrorListResultModel();
            ((ErrorListResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorListResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "加载数据库配置")
    @RequestMapping(value = {"getDbConfigList"}, method = {RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<ProviderConfig>> getDbConfigList() {
        ListResultModel<List<ProviderConfig>> result = new ListResultModel<List<ProviderConfig>>();
        try {
            List<ProviderConfig> configs = getClient().getAllDbConfig();
            result.setData(configs);
        } catch (JDSException e) {
            result = new ErrorListResultModel();
            ((ErrorListResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorListResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "添加数据库配置")
    @RequestMapping(value = {"addDBConfig"}, method = {RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> addDBConfig(@RequestBody ProviderConfig config) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {
            getClient().updateDbConfig(config);
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "增加数据库表")
    @RequestMapping(value = {"addTableNames"}, method = {RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> addTableNames(String projectName, String configKey, String id) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {
            ProjectVersion version = getClient().getProjectVersionByName(projectName);
            ProjectConfig config = version.getProject().getConfig();
            List<String> tableNames = new ArrayList<String>();
            List<String> configKeyList = Arrays.asList(StringUtility.split(id, ";"));
            for (String tableName : configKeyList) {
                if (!tableNames.contains(tableName)) {
                    tableNames.add(tableName);
                }

            }
            DataBaseConfig dataBaseConfig = config.getDataBaseConfigBykey(configKey);
            dataBaseConfig.setTableName(tableNames);
            version.updateConfig(config);
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }

    @MethodChinaName(cname = "删除数据库配置")
    @RequestMapping(value = {"removeDBConfig"}, method = {RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> removeDBConfig(String configKey) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {
            MySpace space = getClient().getSpace();
            MySpaceConfig spaceConfig = space.getConfig();
            List<ProviderConfig> newConfigs = new ArrayList<ProviderConfig>();
            Map<String, ProviderConfig> configMap = spaceConfig.getDbConfig();
            List<String> configKeyList = Arrays.asList(StringUtility.split(configKey, ";"));
            for (String delkey : configKeyList) {
                configMap.remove(delkey);
            }
            getClient().updateSpaceConfig(spaceConfig);
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "删除数据库配置")
    @RequestMapping(value = {"removeDBformPrj"}, method = {RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> removeDBConfig(String configKey, String projectName) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {
            ProjectVersion version = getClient().getProjectVersionByName(projectName);
            ProjectConfig config = version.getProject().getConfig();
            List<String> configKeyList = Arrays.asList(StringUtility.split(configKey, ";"));
            for (String configkey : configKeyList) {
                List<DataBaseConfig> configs = config.getDbConfigs();
                configs.remove(config.getDataBaseConfigBykey(configKey));
            }
            config.setDbConfigs(config.getDbConfigs());
            version.updateConfig(config);
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "添加工程数据库配置")
    @RequestMapping(value = {"addProjectDBConfig"}, method = {RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> addProjectDBConfig(String projectName, String id) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {
            ProjectVersion version = getClient().getProjectVersionByName(projectName);
            ProjectConfig config = version.getProject().getConfig();
            List<String> configKeyList = Arrays.asList(StringUtility.split(id, ";"));
            for (String configkey : configKeyList) {
                DataBaseConfig dataBaseConfig = config.getDataBaseConfigBykey(id);
                if (dataBaseConfig == null) {
                    dataBaseConfig = new DataBaseConfig(configkey);
                    config.addDbConfig(dataBaseConfig);
                }
            }
            config.setDbConfigs(config.getDbConfigs());
            version.updateConfig(config);

        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "更新工程数据库配置")
    @RequestMapping(value = {"updateProjectDBConfig"}, method = {RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> updateDBConfig(String projectName, String configKey, String tableNames, String simpleName, String ftlTemps) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {

            ProjectVersion version = getClient().getProjectVersionByName(projectName);
            ProjectConfig config = version.getProject().getConfig();
            DataBaseConfig dataBaseConfig = config.getDataBaseConfigBykey(configKey);
            if (dataBaseConfig == null) {
                dataBaseConfig = new DataBaseConfig();
                config.addDbConfig(dataBaseConfig);
            }

            if (tableNames != null) {
                String[] tableNameArr = StringUtility.split(tableNames, ";");
                dataBaseConfig.setTableName(Arrays.asList(tableNameArr));
            }
            if (ftlTemps != null) {
                String[] ftlTempArr = StringUtility.split(ftlTemps, ";");
                dataBaseConfig.setFtlTemps(Arrays.asList(ftlTempArr));
            }
            config.setDbConfigs(config.getDbConfigs());
            version.updateConfig(config);

        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }

    @MethodChinaName(cname = "加载数据库配置")
    @RequestMapping(value = {"loadDBConfig"}, method = {RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<DataBaseConfig>> loadDBConfig(String projectName) {
        ListResultModel<List<DataBaseConfig>> result = new ListResultModel<List<DataBaseConfig>>();

        try {
            Project project = getClient().getProjectByName(projectName);
            ProjectConfig projectConfig = project.getConfig();
            List<DataBaseConfig> configKeys = projectConfig.getDbConfigs();
            List<DataBaseConfig> realConfigKeys = new ArrayList<DataBaseConfig>();
            List<DataBaseConfig> errorConfigKeys = new ArrayList<DataBaseConfig>();
            for (DataBaseConfig config : configKeys) {
                String configKey = config.getConfigKey();
                if (configKey != null && this.getClient().getDbConfig(configKey) != null) {
                    config.setProjectName(projectName);
                    realConfigKeys.add(config);
                } else {
                    errorConfigKeys.add(config);
                }
            }

            if (!errorConfigKeys.isEmpty()) {
                configKeys.removeAll(errorConfigKeys);
                getClient().updateProjectConfig(project.getId(), projectConfig);
            }

            result.setData(realConfigKeys);
        } catch (JDSException e) {
            result = new ErrorListResultModel();
            ((ErrorListResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorListResultModel) result).setErrdes(e.getMessage());

        }


        return result;
    }

    @MethodChinaName(cname = "添加文件夹")
    @RequestMapping(value = {"addAPI"}, method = {RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> addAPI(String projectName, String id) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {
            ProjectVersion version = getClient().getProjectVersionByName(projectName);
            String[] ids = StringUtility.split(id, ";");
            ProjectConfig config = version.getProject().getConfig();
            List<String> apis = config.getApiFilter();
            for (String apiId : ids) {
                if (apiId.indexOf(":") == -1) {
                    apiId = APIFactory.LoclHostName + ":" + apiId;
                }
                if (!apis.contains(apiId)) {
                    apis.add(apiId);
                }
            }
            config.setApiFilter(apis);
            version.updateConfig(config);
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = {"getAllService"}, method = {RequestMethod.POST, RequestMethod.GET})
    public ListResultModel<List<APIComponentNode>> getAllService(String pattern) {
        ListResultModel<List<APIComponentNode>> module = new ListResultModel<List<APIComponentNode>>();
        List<APIComponentNode> topMenus = new ArrayList<APIComponentNode>();
        try {
            APIComponentNode userNode = new APIComponentNode("userService", "用户服务", pattern, "xui-icon-dragcopy");
            List<APIPaths> userpaths = this.getClient().getAPITopPaths(pattern, APIType.userdef);
            for (APIPaths apiPaths : userpaths) {
                if (apiPaths.getChildIds().size() > 0) {
                    APIComponentNode componentNode = new APIComponentNode(apiPaths, true, pattern, null);
                    userNode.addSub(componentNode);
                }
            }

            topMenus.add(userNode);


            APIComponentNode loacalNode = new APIComponentNode("loaclServer", "系統系统", pattern, "xui-icon-dragcopy");

            List<APIPaths> paths = this.getClient().getAPITopPaths(pattern, APIType.system);
            for (APIPaths apiPaths : paths) {
                if (apiPaths.getChildIds().size() > 0) {
                    APIComponentNode componentNode = new APIComponentNode(apiPaths, true, pattern, null);
                    if (pattern == null || pattern.equals("")) {
                        componentNode.setIniFold(true);
                    }
                    loacalNode.addSub(componentNode);
                }
            }

            topMenus.add(loacalNode);

            APIComponentNode serverNode = new APIComponentNode("allServer", "远程服务", pattern, "xui-icon-upload");
            List<APIComponentNode> servers = new ArrayList<APIComponentNode>();
            List<ServerNode> serviceBeans = JDSServer.getClusterClient().getAllServer();
            for (ServerNode bean : serviceBeans) {
                if (bean.getServices().size() > 0) {
                    //  APIComponentNode serverApiNode = new APIComponentNode(bean);
                    APIComponentNode serverAPI = new APIComponentNode(getClient().getAPIPaths(bean.getId() + ":/"), true, pattern, null);
                    serverAPI.setImageClass("xui-uicmd-cmdbox");
                    if (pattern == null || pattern.equals("")) {
                        serverAPI.setIniFold(true);
                    }
                    serverNode.addSub(serverAPI);
                }
            }

            topMenus.add(serverNode);

            module.setData(topMenus);
        } catch (JDSException e) {
            module = new ErrorListResultModel();
            ((ErrorListResultModel) module).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorListResultModel) module).setErrdes(e.getMessage());
        }


        return module;
    }

    @ResponseBody
    @RequestMapping(value = {"getAllLoclService"}, method = {RequestMethod.POST, RequestMethod.GET})
    public ListResultModel<List<APIComponentNode>> getAllLoclService(String pattern) {
        ListResultModel<List<APIComponentNode>> module = new ListResultModel<List<APIComponentNode>>();
        List<APIComponentNode> topMenus = new ArrayList<APIComponentNode>();


        try {
            List<APIPaths> paths = this.getClient().getAPITopPaths(pattern, APIType.local);
            for (APIPaths apiPaths : paths) {
                if (apiPaths.getChildIds().size() > 0) {
                    APIComponentNode componentNode = new APIComponentNode(apiPaths, true, pattern, null);
                    topMenus.add(componentNode);
                }

            }
            module.setData(topMenus);
        } catch (JDSException e) {
            module = new ErrorListResultModel();
            ((ErrorListResultModel) module).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorListResultModel) module).setErrdes(e.getMessage());
        }


        return module;
    }


    @MethodChinaName(cname = "移除配置")
    @RequestMapping(value = {"deleteAPIConfig"}, method = {RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> deleteAPIConfig(String projectName, String id) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {
            ProjectVersion version = getClient().getProjectVersionByName(projectName);
            ProjectConfig projectConfig = version.getProject().getConfig();
            List<String> idList = projectConfig.getApiFilter();
            String[] ids = StringUtility.split(id, ";");

            List<String> allapiIds = new ArrayList<String>();
            allapiIds.addAll(Arrays.asList(ids));
            //移除垃圾数据
            for (String cid : idList) {
                APIPaths apiPaths = this.getClient().getAPIPaths(cid);
                if (apiPaths == null) {
                    allapiIds.add(cid);
                }
            }

            for (String cid : allapiIds) {
                idList.remove(cid);
                if (cid.indexOf(":") == -1) {
                    cid = APIFactory.LoclHostName + ":" + cid;
                }
                idList.remove(cid);
            }
            version.updateConfig(projectConfig);
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "获取配置")
    @RequestMapping(value = {"getAPIConfig"}, method = {RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<APIComponentNode>> getAPIConfig(String projectName, String id) {
        ListResultModel<List<APIComponentNode>> result = new ListResultModel<List<APIComponentNode>>();
        try {
            ESDClient client = ESDFacrory.getESDClient();


            List<APICallerProperties> configs = client.getAPIMethodsByProject(projectName);
            result = PageUtil.getDefaultPageList(configs, APIComponentNode.class);
        } catch (JDSException e) {
            result = new ErrorListResultModel<>();
            ((ErrorListResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorListResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    public ESDClient getClient() throws JDSException {

        ESDClient client = ESDFacrory.getESDClient();

        return client;
    }
}
